package com.hshit.downloader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.SearchView;

import com.hshit.downloader.adapter.ActionFragmentAdapter;
import com.hshit.downloader.custom.PagerListener;
import com.hshit.downloader.custom.PagerSlidingTabStrip;
import com.hshit.downloader.fragment.BaseFragment;
import com.hshit.downloader.fragment.DownloadStatusFragment;
import com.hshit.downloader.fragment.Mp3Fragment;
import com.hshit.downloader.models.TrackInfo;
import com.hshit.downloader.utils.Constants;
import com.hshit.downloader.utils.Utility;

public class MainActivity extends FragmentActivity implements PagerListener {
	private PagerSlidingTabStrip tabs;

	private ViewPager pager;

	private ActionFragmentAdapter adapter;

	private int currentColor = 0xFF5161BC;

	private Drawable oldBackground = null;

	private final Handler handler = new Handler();

	private String keyword = "";

	List<TrackInfo> mListTracks = new ArrayList<TrackInfo>();

	List<TrackInfo> mListTracksDownloading = new ArrayList<TrackInfo>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pager = (ViewPager) findViewById(R.id.pager);
		tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);

		adapter = new ActionFragmentAdapter(getSupportFragmentManager());

		pager.setAdapter(adapter);

		final int pageMargin = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
						.getDisplayMetrics());
		pager.setPageMargin(pageMargin);

		pager.setOffscreenPageLimit(2);

		tabs.setViewPager(pager, this);

		changeColor(currentColor);

		setDefaultDirectory();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu_layout, menu);
		MenuItem searchItem = menu.findItem(R.id.action_search);
		final SearchView searchView = (SearchView) searchItem.getActionView();
		searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextSubmit(String s) {
				String key = keyword.trim().replace(" ", "%20");
				if (!key.equals("")) {
					callSearching(key);
					Utility.hideSoftInputFromWindow(searchView, MainActivity.this);
				}
				return false;
			}

			@Override
			public boolean onQueryTextChange(String s) {
				keyword = s;
				return false;
			}
		});
		searchView.setOnSearchClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});

		return super.onCreateOptionsMenu(menu);

	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	private void changeColor(int newColor) {
		tabs.setIndicatorColor(newColor);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

			Drawable colorDrawable = new ColorDrawable(newColor);
			Drawable bottomDrawable = getResources().getDrawable(
					R.drawable.view_sliding_tab_actionbar_bottom);
			LayerDrawable ld = new LayerDrawable(new Drawable[] {
					colorDrawable, bottomDrawable });

			if (oldBackground == null) {

				if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
					ld.setCallback(drawableCallback);
				} else {
					getActionBar().setBackgroundDrawable(ld);
				}

			} else {

				TransitionDrawable td = new TransitionDrawable(new Drawable[] {
						oldBackground, ld });

				if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
					td.setCallback(drawableCallback);
				} else {
					getActionBar().setBackgroundDrawable(td);
				}

				td.startTransition(200);

			}

			oldBackground = ld;

			getActionBar().setDisplayShowTitleEnabled(false);
			getActionBar().setDisplayShowTitleEnabled(true);

		}

		currentColor = newColor;
	}

	private Drawable.Callback drawableCallback = new Drawable.Callback() {
		@Override
		public void invalidateDrawable(Drawable who) {
			getActionBar().setBackgroundDrawable(who);
		}

		@Override
		public void scheduleDrawable(Drawable who, Runnable what, long when) {
			handler.postAtTime(what, when);
		}

		@Override
		public void unscheduleDrawable(Drawable who, Runnable what) {
			handler.removeCallbacks(what);
		}
	};

	public void onColorClicked(View v) {
		int color = Color.parseColor(v.getTag().toString());
		changeColor(color);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("currentColor", currentColor);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		currentColor = savedInstanceState.getInt("currentColor");
		changeColor(currentColor);
	}

	int mCurrentFragment = BaseFragment.TAB_MP3;

	public void setCurrenFragment(int mode_fragment) {
		mCurrentFragment = mode_fragment;
	}

	public int getCurrentFragment() {
		return this.mCurrentFragment;
	}

	@Override
	public void onChangeTab(int mode) {
		setCurrenFragment(mode);
	}

	public List<TrackInfo> getListTrack() {
		return this.mListTracks;
	}

	public void setListTrack(List<TrackInfo> mListTracks) {
		this.mListTracks = mListTracks;
	}

	public List<TrackInfo> getListTrackDownloading() {
		return this.mListTracksDownloading;
	}

	public void setListTrackDownloading(List<TrackInfo> mListTracks) {
		this.mListTracksDownloading = mListTracks;
	}

	public void addNewDownloading(TrackInfo item) {
		if (!mListTracksDownloading.contains(item)) {
			mListTracksDownloading.add(item);
			callDownloadFragment(item);
		}
	}

	private void callDownloadFragment(TrackInfo item) {
		((DownloadStatusFragment) adapter
				.getFragmentTab(BaseFragment.TAB_DOWNLOAD)).showListView(item);
	}

	private void callSearching(String keyword) {
		((Mp3Fragment) adapter.getFragmentTab(BaseFragment.TAB_MP3))
				.fetchSearchResult(keyword);
	}

	private void setDefaultDirectory() {
		File directory = new File(Constants.DEFAULT_FOLDER);
		if (!directory.exists())
			directory.mkdir();
	}

}
